from tkinter import *
import tkinter.messagebox
from tkinter import ttk
from tkinter import font
from src.backend.room_b import RoomBackend

class RoomFrontend:
    """Frontend UI for room management"""
    
    def __init__(self, master, user_type='admin'):
        self.master = master
        self.user_type = user_type
        self.backend = RoomBackend()
        
        self.master.title("HOSPITAL MANAGEMENT SYSTEM")
        self.master.geometry("1500x700+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()

        #ATTRIBUTES
        self.room_number = StringVar()
        self.room_type = StringVar()
        self.capacity = IntVar()
        self.rate_per_day = StringVar()
        self.floor_number = IntVar()
        self.dept_id = IntVar()
        self.patient_id = IntVar()

        self.create_ui()

    def create_ui(self):
        """Create the user interface"""
        #=TITLE===
        self.lblTitle = Label(self.frame, text="ROOM ALLOCATION FORM", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=50)
        
        #FRAME===
        self.LoginFrame = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame.grid(row=1, column=0)
        
        self.LoginFrame2 = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame2.grid(row=2, column=0)
        
        self.create_form_fields()
        self.create_buttons()

    def create_form_fields(self):
        """Create form input fields"""
        #====LABELS         
        self.lblroomno = Label(self.LoginFrame, text="ROOM NUMBER", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblroomno.grid(row=0, column=0)
        self.lblroomno = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.room_number)
        self.lblroomno.grid(row=0, column=1)
        
        self.lblroomtype = Label(self.LoginFrame, text="ROOM TYPE", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblroomtype.grid(row=1, column=0)
        self.lblroomtype = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.room_type)
        self.lblroomtype.grid(row=1, column=1)
        
        self.lblcapacity = Label(self.LoginFrame, text="CAPACITY", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblcapacity.grid(row=2, column=0)
        self.lblcapacity = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.capacity)
        self.lblcapacity.grid(row=2, column=1)
        
        self.lblrate = Label(self.LoginFrame, text="RATE PER DAY", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblrate.grid(row=0, column=2)
        self.lblrate = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.rate_per_day)
        self.lblrate.grid(row=0, column=3)
        
        self.lblfloor = Label(self.LoginFrame, text="FLOOR NUMBER", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblfloor.grid(row=1, column=2)
        self.lblfloor = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.floor_number)
        self.lblfloor.grid(row=1, column=3)
        
        self.lbldept = Label(self.LoginFrame, text="DEPARTMENT ID", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lbldept.grid(row=2, column=2)
        self.lbldept = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.dept_id)
        self.lbldept.grid(row=2, column=3)
        
        self.lblpatient = Label(self.LoginFrame, text="PATIENT ID (for assignment)", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblpatient.grid(row=3, column=0)
        self.lblpatient = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.patient_id)
        self.lblpatient.grid(row=3, column=1)

    def create_buttons(self):
        """Create action buttons"""
        #====BUTTONS
        self.button2 = Button(self.LoginFrame2, text="SUBMIT", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.INSERT_ROOM)
        self.button2.grid(row=3, column=1, padx=5, pady=5)
        
        self.button3 = Button(self.LoginFrame2, text="UPDATE", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.UPDATE_ROOM)
        self.button3.grid(row=3, column=2, padx=5, pady=5)
        
        self.button5 = Button(self.LoginFrame2, text="ROOM DETAILS", width=15, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.SEARCH_ROOM)
        self.button5.grid(row=3, column=4, padx=5, pady=5)
        
        self.button6 = Button(self.LoginFrame2, text="EXIT", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.Exit)
        self.button6.grid(row=3, column=5, padx=5, pady=5)
        
        if self.user_type == 'root':
            self.btn_global = Button(self.LoginFrame2, text="GLOBAL SEARCH", width=15, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.GLOBAL_ROOMS)
            self.btn_global.grid(row=4, column=1, columnspan=2, pady=10)
        
    #FUNCTION TO INSERT DATA IN ROOM ALLOCATION FORM
    def INSERT_ROOM(self):
        try:
            # Validate capacity (must be positive integer)
            capacity = self.capacity.get()
            if capacity <= 0:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Capacity must be a positive integer (whole number)")
                return
            
            # Get form data
            room_data = {
                'room_number': self.room_number.get().strip(),
                'room_type': self.room_type.get().strip(),
                'capacity': capacity,
                'rate_per_day': self.rate_per_day.get().strip(),
                'floor_number': self.floor_number.get(),
                'dept_id': self.dept_id.get()
            }
            
            # Validate data
            is_valid, message = self.backend.validate_room_data(room_data)
            if not is_valid:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", message)
                return
            
            # Add room to database
            if self.backend.add_room(room_data):
                tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Room added successfully")
                
                # If patient ID is provided, assign room to patient
                patient_id = self.patient_id.get()
                if patient_id:
                    if self.backend.assign_room_to_patient(room_data['room_number'], patient_id):
                        tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", f"Room {room_data['room_number']} assigned to patient {patient_id}")
                    else:
                        tkinter.messagebox.showwarning("HOSPITAL DATABASE SYSTEM", "Room added but failed to assign to patient")
                
                self.clear_form()
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to add room")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
    
    def clear_form(self):
        """Clear all form fields"""
        self.room_number.set("")
        self.room_type.set("")
        self.capacity.set(0)
        self.rate_per_day.set("")
        self.floor_number.set(0)
        self.dept_id.set(0)
        self.patient_id.set(0)
            
    #FUNCTION TO OPEN SEARCH MENU IN ROOM ALLOCATION FORM
    def SEARCH_ROOM(self):
        self.newWindow = Toplevel(self.master)
        self.app = S_Room(self.newWindow, self.backend)
        
    #FUNCTION TO EXIT ROOM ALLOCATION FORM
    def Exit(self):            
        self.master.destroy()   

    #FUNCTION TO UPDATE DATA IN ROOM ALLOCATION FORM       
    def UPDATE_ROOM(self):
        try:
            room_number = self.room_number.get().strip()
            if not room_number:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Please enter Room Number to update")
                return
            
            # Check if room exists
            room = self.backend.get_room(room_number)
            if not room:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Room not found")
                return
            
            # Get form data
            update_data = {}
            if self.room_type.get().strip():
                update_data['room_type'] = self.room_type.get().strip()
            
            # For capacity: allow any positive integer (0 means not set)
            # Capacity must be a whole number (integer), not decimal
            capacity = self.capacity.get()
            if capacity > 0:
                # Validate it's an integer (IntVar should handle this, but double-check)
                if not isinstance(capacity, int) or capacity != int(capacity):
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Capacity must be a whole number (integer), not a decimal")
                    return
                update_data['capacity'] = capacity
            
            if self.rate_per_day.get().strip():
                update_data['rate_per_day'] = float(self.rate_per_day.get().strip())
            
            # For optional integer fields: 0 means not set/NULL
            floor = self.floor_number.get()
            if floor > 0:
                update_data['floor_number'] = floor
            elif floor == 0:
                update_data['floor_number'] = None
            
            dept = self.dept_id.get()
            if dept > 0:
                update_data['dept_id'] = dept
            elif dept == 0:
                update_data['dept_id'] = None
            
            patient = self.patient_id.get()
            if patient > 0:
                update_data['patient_id'] = patient
            elif patient == 0:
                update_data['patient_id'] = None
            
            if not update_data:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "No data to update")
                return
            
            # Update room
            if self.backend.update_room(room_number, update_data):
                tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Room updated successfully")
                self.clear_form()
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to update room")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")

    def GLOBAL_ROOMS(self):
        """Open global room search window with full CRUD functionality"""
        self.newWindow = Toplevel(self.master)
        self.app = GlobalRoomSearchMenu(self.newWindow, self.backend)

#CLASS FOR DISPLAY MENU FOR SEARCH ROOM
class S_Room:
    def __init__(self, master, backend):    
        self.master = master
        self.backend = backend
        self.master.title("HOSPITAL MANAGEMENT SYSTEM")
        self.master.geometry("1500x700+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        self.Pr_id = IntVar()
        self.lblTitle = Label(self.frame, text="SEARCH PATIENT DETAILS", font="Arial 16 bold", bg="#C0C0C0")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=25)
        #FRAME
        self.LoginFrame = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame.grid(row=1, column=0)
        self.LoginFrame2 = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame2.grid(row=2, column=0)
        
        #LABELS         
        self.lblpatid = Label(self.LoginFrame, text="ENTER PATIENT ID TO SEARCH", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblpatid.grid(row=0, column=0)
        self.lblpatid = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.Pr_id)
        self.lblpatid.grid(row=0, column=1)

        self.SearchB = Button(self.LoginFrame2, text="SEARCH", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.ROOM_DISPLAY)
        self.SearchB.grid(row=0, column=1, padx=5, pady=5)    

    #FUNCTION TO SEARCH DATA IN ROOM ALLOCATION FORM
    def ROOM_DISPLAY(self):
        try:
            patient_id = self.Pr_id.get()
            if not patient_id:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Please enter Patient ID to search")
                return
            
            # Get room information for patient
            rooms = self.backend.get_all_rooms()
            patient_room = None
            
            # Database fields: room_number(0), room_type(1), capacity(2), rate_per_day(3),
            # floor_number(4), dept_id(5), status(6), patient_id(7), admission_date(8), discharge_date(9)
            for room in rooms:
                if room[7] == patient_id:  # Check if patient_id matches (room[7], not room[6]!)
                    patient_room = room
                    break
            
            if not patient_room:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "PATIENT NOT ALLOCATED ROOM")
            else:
                # Display room information
                self.l1 = Label(self.LoginFrame, text="PATIENT ID", font="Arial 11 bold", bg="#C0C0C0", bd=22)
                self.l1.grid(row=1, column=0)
                self.dis1 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=patient_id)
                self.dis1.grid(row=1, column=1)
                        
                self.l2 = Label(self.LoginFrame, text="ROOM NO", font="Arial 11 bold", bg="#C0C0C0", bd=22)
                self.l2.grid(row=2, column=0)
                self.dis2 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=patient_room[0])
                self.dis2.grid(row=2, column=1)

                self.l3 = Label(self.LoginFrame, text="ROOM TYPE", font="Arial 11 bold", bg="#C0C0C0", bd=22)
                self.l3.grid(row=1, column=2)
                self.dis3 = Label(self.LoginFrame, font="Arial 11 bold", bg="#C0C0C0", bd=2, text=patient_room[1])
                self.dis3.grid(row=1, column=3)

                self.l4 = Label(self.LoginFrame, text="CAPACITY", font="Arial 11 bold", bg="#C0C0C0", bd=22)
                self.l4.grid(row=2, column=2)
                self.dis4 = Label(self.LoginFrame, font="Arial 11 bold", bg="#C0C0C0", bd=2, text=patient_room[2])
                self.dis4.grid(row=2, column=3)
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")

#CLASS FOR GLOBAL ROOM SEARCH MENU (ROOT ONLY)
class GlobalRoomSearchMenu:
    def __init__(self, master, backend):    
        self.master = master
        self.backend = backend
        self.master.title("GLOBAL SEARCH - ALL ROOMS")
        self.master.geometry("1200x600+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        
        self.lblTitle = Label(self.frame, text="GLOBAL ROOM SEARCH", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=25)
        
        # Create Treeview for displaying all rooms
        self.tree_frame = Frame(self.frame, bg="#C0C0C0")
        self.tree_frame.grid(row=1, column=0, padx=20, pady=10)
        
        # Define columns
        columns = ('Room No', 'Type', 'Capacity', 'Rate/Day', 'Floor', 'Dept ID', 'Patient ID')
        self.tree = ttk.Treeview(self.tree_frame, columns=columns, show='headings', height=15)
        
        # Define headings
        for col in columns:
            self.tree.heading(col, text=col)
            self.tree.column(col, width=120)
        
        # Add scrollbar
        scrollbar = ttk.Scrollbar(self.tree_frame, orient=VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar.set)
        
        # Pack treeview and scrollbar
        self.tree.pack(side=LEFT, fill=BOTH, expand=True)
        scrollbar.pack(side=RIGHT, fill=Y)
        
        # Buttons frame
        self.button_frame = Frame(self.frame, bg="#C0C0C0")
        self.button_frame.grid(row=2, column=0, pady=10)
        
        self.refresh_btn = Button(self.button_frame, text="REFRESH", width=15, font="Arial 11 bold", 
                                bg="#C0C0C0", relief="raised", bd=2, command=self.refresh_data)
        self.refresh_btn.pack(side=LEFT, padx=5)
        
        self.edit_btn = Button(self.button_frame, text="EDIT SELECTED", width=15, font="Arial 11 bold", 
                              bg="#C0C0C0", relief="raised", bd=2, command=self.edit_selected)
        self.edit_btn.pack(side=LEFT, padx=5)
        
        self.delete_btn = Button(self.button_frame, text="DELETE SELECTED", width=15, font="Arial 11 bold", 
                                bg="#C0C0C0", relief="raised", bd=2, command=self.delete_selected)
        self.delete_btn.pack(side=LEFT, padx=5)
        
        self.close_btn = Button(self.button_frame, text="CLOSE", width=15, font="Arial 11 bold", 
                               bg="#C0C0C0", relief="raised", bd=2, command=self.close_window)
        self.close_btn.pack(side=LEFT, padx=5)
        
        # Load initial data
        self.refresh_data()
    
    def refresh_data(self):
        """Refresh the room data in the treeview"""
        try:
            # Clear existing data
            for item in self.tree.get_children():
                self.tree.delete(item)
            
            # Get all rooms from database
            rooms = self.backend.get_all_rooms()
            
            # Insert data into treeview
            # Database fields: room_number(0), room_type(1), capacity(2), rate_per_day(3),
            # floor_number(4), dept_id(5), status(6), patient_id(7), admission_date(8), discharge_date(9)
            for room in rooms:
                self.tree.insert('', 'end', values=(
                    room[0],  # Room No
                    room[1],  # Type
                    room[2],  # Capacity
                    room[3],  # Rate/Day
                    room[4] if room[4] is not None else "N/A",  # Floor
                    room[5] if room[5] is not None else "N/A",  # Dept ID
                    room[7] if room[7] is not None else "N/A"   # Patient ID (room[7], not room[6]!)
                ))
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error loading data: {str(e)}")
    
    def edit_selected(self):
        """Edit the selected room"""
        selection = self.tree.selection()
        if not selection:
            tkinter.messagebox.showwarning("HOSPITAL DATABASE SYSTEM", "Please select a room to edit")
            return
        
        # Get selected room data
        item = self.tree.item(selection[0])
        room_number = item['values'][0]
        
        # Open edit window
        self.edit_window = Toplevel(self.master)
        self.edit_app = EditRoomWindow(self.edit_window, room_number, self.backend, self.refresh_data)
    
    def delete_selected(self):
        """Delete the selected room"""
        selection = self.tree.selection()
        if not selection:
            tkinter.messagebox.showwarning("HOSPITAL DATABASE SYSTEM", "Please select a room to delete")
            return
        
        # Get selected room data
        item = self.tree.item(selection[0])
        room_number = item['values'][0]
        room_type = item['values'][1]
        
        # Confirm deletion
        result = tkinter.messagebox.askyesno("HOSPITAL DATABASE SYSTEM", 
                                           f"Are you sure you want to delete room {room_number} ({room_type})?")
        if result:
            try:
                if self.backend.delete_room(room_number):
                    tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Room deleted successfully")
                    self.refresh_data()
                else:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to delete room")
            except Exception as e:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
    
    def close_window(self):
        """Close the global search window"""
        self.master.destroy()

#CLASS FOR EDIT ROOM WINDOW
class EditRoomWindow:
    def __init__(self, master, room_number, backend, refresh_callback):
        self.master = master
        self.room_number = room_number
        self.backend = backend
        self.refresh_callback = refresh_callback
        
        self.master.title("EDIT ROOM")
        self.master.geometry("800x600+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        
        # Get room data
        self.room = self.backend.get_room(room_number)
        if not self.room:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Room not found")
            self.master.destroy()
            return
        
        # Create form variables
        # Database fields: room_number(0), room_type(1), capacity(2), rate_per_day(3),
        # floor_number(4), dept_id(5), status(6), patient_id(7)
        self.room_type = StringVar(value=self.room[1])
        self.capacity = IntVar(value=self.room[2])
        self.rate_per_day = StringVar(value=str(self.room[3]))
        self.floor_number = IntVar(value=self.room[4] or 0)
        self.dept_id = IntVar(value=self.room[5] or 0)
        self.patient_id = IntVar(value=self.room[7] or 0)  # room[7] is patient_id!
        
        # Title
        self.lblTitle = Label(self.frame, text="EDIT ROOM", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=20)
        
        # Form frame
        self.form_frame = Frame(self.frame, bg="#C0C0C0")
        self.form_frame.grid(row=1, column=0, padx=20, pady=10)
        
        # Form fields
        row = 0
        Label(self.form_frame, text="ROOM NUMBER:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Label(self.form_frame, text=room_number, font="Arial 11", bg="#C0C0C0").grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="ROOM TYPE:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.room_type, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="CAPACITY:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.capacity, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="RATE PER DAY:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.rate_per_day, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="FLOOR NUMBER:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.floor_number, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="DEPARTMENT ID:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.dept_id, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="PATIENT ID:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.patient_id, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        
        # Buttons
        self.button_frame = Frame(self.frame, bg="#C0C0C0")
        self.button_frame.grid(row=2, column=0, pady=20)
        
        Button(self.button_frame, text="SAVE", width=15, font="Arial 11 bold", 
               bg="#C0C0C0", relief="raised", bd=2, command=self.save_changes).pack(side=LEFT, padx=5)
        Button(self.button_frame, text="CANCEL", width=15, font="Arial 11 bold", 
               bg="#C0C0C0", relief="raised", bd=2, command=self.master.destroy).pack(side=LEFT, padx=5)
    
    def save_changes(self):
        """Save the changes to the room"""
        try:
            # Validate capacity (must be positive integer)
            capacity = self.capacity.get()
            if capacity <= 0:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Capacity must be a positive integer (whole number)")
                return
            
            # Ensure capacity is integer (not float)
            if not isinstance(capacity, int):
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Capacity must be a whole number (integer), not a decimal")
                return
            
            # Prepare update data
            update_data = {
                'room_type': self.room_type.get().strip(),
                'capacity': capacity,
                'rate_per_day': float(self.rate_per_day.get().strip()),
                'floor_number': self.floor_number.get() if self.floor_number.get() > 0 else None,
                'dept_id': self.dept_id.get() if self.dept_id.get() > 0 else None,
                'patient_id': self.patient_id.get() if self.patient_id.get() > 0 else None
            }
            
            if self.backend.update_room(self.room_number, update_data):
                tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Room updated successfully")
                self.refresh_callback()
                self.master.destroy()
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to update room")
                
        except ValueError as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Invalid input: Please enter valid numbers")
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")

